from zope.interface import implements, Interface

from Products.Five import BrowserView
from Products.CMFCore.utils import getToolByName
from plone.memoize.instance import memoize
from zope.component import getUtility
#from zope.i18n.interfaces import ITranslationDomain
#from zope.component import queryUtility
from Products.CMFCore.interfaces import ISiteRoot
from Products.AdvancedQuery import Eq, Between, Le

from my315ok.fangcan import fangcanMessageFactory as _
from my315ok.fangcan.browser.fangcansearchview import fangcansearchView
from my315ok.fangcan.interfaces import Ihouse


class Isecondhouse_listsView(Interface):
    """
    secondhouse_lists view interface
    """

    def test():
        """ test method"""


class secondhouse_listsView(fangcansearchView):
    """
    secondhouse_lists browser view
    """
    implements(Isecondhouse_listsView)

    @memoize
    def query(self):
        """
        compose secondhand house query string
        """
        portal = getUtility(ISiteRoot)
        cat = getToolByName(portal, 'portal_catalog')
#        cat = getToolByName(context, 'portal_catalog')
        aq = cat.makeAdvancedQuery({'object_provides' : Ihouse.__identifier__,'category':'1', 'review_state' : 'published'})
        raw = self.request["QUERY_STRING"]

        if "SearchableText" in self.request.form.keys():
            term = self.request.form["SearchableText"]
            term = term.strip()
            if len(term)!=0:
                query = Eq("SearchableText",term) | Eq('Description',term)
                return query               
        
        elif len(raw) != 0:
            phase = raw.split("&")
            for st2 in phase:                
                st = st2.split("=")
                pa = st[0]
                val = st[-1]            
                if "-" in val:
#                op = Between
                    low = val.split("-")[0]
                    hight = val.split("-")[-1]
                    query = Between(pa,float(low),float(hight))                
                else:
#                op = Eq
                    query = Eq(pa, val)
#                aq = query
                aq &= query 
            return query
        else:
            return aq

